<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="菜单名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleEnable">
        批量启用
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-edit" @click="handleDisable">
        批量禁用
      </el-button>
    </div>

    <el-table
      :data="tableData"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      @selection-change="tableSelected"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        prop="name"
        label="菜单名称"
        sortable
        width="380"
      />
      <el-table-column
        prop="seq"
        width="80"
        label="显示顺序"
      />
      <el-table-column
        prop="url"
        width="580"
        label="请求地址"
      />
      <el-table-column
        prop="status"
        width="120"
        label="状态"
      >
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status==true"
            size="mini"
            @click="handleEditStatus(scope.$index, scope.row,0)"
          >启用</el-button>
          <el-button
            v-if="scope.row.status==false"
            size="mini"
            type="danger"
            @click="handleEditStatus(scope.$index, scope.row,1)"
          >禁用</el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="buttons"
        label="按钮"
      >
        <template slot-scope="scope">
          <el-row>
            <label v-for="btn in scope.row.buttons" :key="btn.id" class="menu-btn" size="mini">{{ btn.name }}</label>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            @click="handleButton(scope.$index, scope.row)"
          >按钮</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="150">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="上级" prop="pid">
          <el-tree
            ref="tree"
            v-model="temp.pid"
            :data="menuData"
            show-checkbox
            node-key="id"
            check-strictly="true"
            :props="menuTreeProps"
            @check-change="menuTreeCheck"
          />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="seq">
          <el-input v-model="temp.seq" />
        </el-form-item>
        <el-form-item label="Icon" prop="icon">
          <el-input v-model="temp.icon" clearable="true" @focus="handleMenuIcon" />
        </el-form-item>
        <el-form-item label="url" prop="url">
          <el-input v-model="temp.url" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="temp.status"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="Icons" :visible.sync="dialogIconVisible">
      <div class="grid">
        <div v-for="item of svgIcons" :key="item" @dblclick="selectIcon(item)">
          <el-tooltip placement="top">
            <div slot="content">
              双击选中
            </div>
            <div class="icon-item">
              <svg-icon :icon-class="item" class-name="disabled" />
              <span>{{ item }}</span>
            </div>
          </el-tooltip>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogIconVisible = false">
          取消
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="btnTitle" :visible.sync="dialogButtonVisible">
      <div>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-plus" size="mini" @click="handleAddBtn">
          添加
        </el-button>
      </div>
      <div style="width:100%;">
        <el-form ref="btnDataForm" :model="btnDataForm" :rules="btnRules">
          <el-table
            :data="btnDataForm.btnData"
            height="250"
            border
            style="width: 100%"
          >
            <el-table-column
              prop="name"
              label="按钮名称"
              width="180"
            >
              <template slot-scope="scope">
                <el-form-item :prop="'btnData.' + scope.$index + '.name'" :rules="btnRules.name">
                  <el-input v-model="scope.row.name" placeholder="按钮名称" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="code"
              label="编码"
              width="180"
            >
              <template slot-scope="scope">
                <el-form-item :prop="'btnData.' + scope.$index + '.code'" :rules="btnRules.code">
                  <el-input v-model="scope.row.code" placeholder="编码" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              prop="icon"
              label="图标"
              width="180"
            >
              <template slot-scope="scope">
                <el-input v-model="scope.row.icon" placeholder="图标" :clearable="true" @focus="handleBtnIcon(scope.$index, scope.row)" />
              </template>
            </el-table-column>
            <el-table-column
              prop="status"
              label="启用/禁用"
            >
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.status"
                  active-text="启用"
                  inactive-text="禁用"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleRemoveBtn(scope.$index, scope.row)"
                >移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogButtonVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="saveMenuBtn">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { page, update, create, setStatus, saveBtn } from '@/api/menu'
import { parseTime } from '@/utils'
import svgIcons from '../../icons/svg-icons'
import waves from '@/directive/waves' // waves directive

export default {
  name: 'ComplexTable',
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      tableData: [],
      menuData: [],
      svgIcons,
      total: 0,
      listLoading: true,
      dialogIconVisible: false,
      listQuery: {
        page: 1,
        limit: 20,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },
      menuTreeProps: {
        label: 'name'
      },
      showReviewer: false,
      temp: {
        id: undefined,
        pid: 0,
        icon: '',
        seq: 0,
        name: '',
        url: '',
        status: true
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        name: [{ required: true, message: 'name is required', trigger: 'blur' }]
      },
      btnRules: {
        code: [{ required: true, message: 'code is required', trigger: 'blur' }],
        name: [{ required: true, message: 'name is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      tableSelectedKeys: [],
      dialogButtonVisible: false,
      iconType: '',
      btnIconIndex: -1,
      menuSelectedRow: {},
      btnDataForm: {
        btnData: []
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      page(this.listQuery).then(response => {
        this.tableData = response.data.data
        this.menuData = this.tableData

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        pid: 0,
        icon: '',
        seq: 0,
        name: '',
        url: '',
        status: true
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          create(tempData).then(res => {
            const response = res.data
            if (response.success) {
              this.getList()
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.msg,
                type: 'failed'
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          update(tempData).then(res => {
            const response = res.data
            if (response.success) {
              this.getList()
              this.dialogFormVisible = false
            } else {
              this.$message({
                message: response.msg,
                type: 'failed'
              })
            }
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$notify({
        title: 'Success',
        message: 'Delete Successfully',
        type: 'success',
        duration: 2000
      })
      this.list.splice(index, 1)
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    handleEditStatus(index, row, status) {
      return true
    },
    handleEdit(index, row) {
      this.dialogFormVisible = true
      this.temp = row
      this.$refs.tree.setCheckedKeys([row.pid])
      this.dialogStatus = 'update'
    },
    handleButton(index, row) {
      this.dialogButtonVisible = true
      this.btnTitle = '菜单：' + row.name + '按钮'
      this.menuSelectedRow = row
      this.btnDataForm.btnData = row.buttons
    },
    handleAddBtn() {
      this.btnDataForm.btnData.push({ name: '', code: '', status: true, icon: '', menuId: this.menuSelectedRow.id })
    },
    handleBtnIcon(index, row) {
      this.dialogIconVisible = true
      this.iconType = 'btn'
      this.btnIconIndex = index
    },
    handleMenuIcon() {
      this.dialogIconVisible = true
      this.iconType = 'menu'
    },
    handleRemoveBtn(index, row) {
      this.btnDataForm.btnData.splice(index, 1)
    },
    saveMenuBtn() {
      this.$refs['btnDataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign([], this.btnDataForm.btnData)
          if (tempData.length == 0) {
            this.dialogButtonVisible = false
            return false
          }
          saveBtn(tempData).then(res => {
            const response = res.data
            if (response.success) {
              this.dialogButtonVisible = false
              this.getList()
            } else {
              this.$message({
                message: response.msg,
                type: 'failed'
              })
            }
          })
        }
      })
    },
    generateIconCode(symbol) {
      return `<svg-icon icon-class="${symbol}" />`
    },
    selectIcon(symbol) {
      this.dialogIconVisible = false
      if (this.iconType === 'menu') {
        this.temp.icon = symbol
      } else {
        this.btnDataForm.btnData[this.btnIconIndex].icon = symbol
      }
    },
    menuTreeCheck(data, checked, node) {
      if (checked) {
        this.$refs.tree.setCheckedNodes([data])
        this.temp.pid = this.$refs.tree.getCheckedKeys()[0]
      }
    },
    tableSelected(selectedData) {
      this.tableSelectedKeys = []
      selectedData.forEach(a => {
        this.tableSelectedKeys.push(a.id)
      })
    },
    handleEnable() {
      if (this.tableSelectedKeys.length === 0) {
        this.$message({
          message: '请先选择需要设置的数据。',
          type: 'success'
        })
        return false
      } else {
        setStatus({ ids: this.tableSelectedKeys, status: true }).then(res => {
          const response = res.data
          if (response.success) {
            this.getList()
            this.dialogFormVisible = false
          } else {
            this.$message({
              message: response.msg,
              type: 'failed'
            })
          }
        })
      }
    },
    handleDisable() {
      if (this.tableSelectedKeys.length === 0) {
        this.$message({
          message: '请先选择需要设置的数据。',
          type: 'success'
        })
        return false
      } else {
        setStatus({ ids: this.tableSelectedKeys, status: false }).then(res => {
          const response = res.data
          if (response.success) {
            this.getList()
            this.dialogFormVisible = false
          } else {
            this.$message({
              message: response.msg,
              type: 'failed'
            })
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.grid {
    position: relative;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  }

  .icon-item {
    margin: 20px;
    height: 85px;
    text-align: center;
    width: 100px;
    float: left;
    font-size: 30px;
    color: #24292e;
    cursor: pointer;
  }

  span {
    display: block;
    font-size: 16px;
    margin-top: 10px;
  }

  .disabled {
    pointer-events: none;
  }

  .menu-btn {
    padding: 7px 5px;
    margin-right: 5px;
    border-radius: 3px;
    font-size: 12px;
    background-color: #fff;
    border-color: #b3d8ff;
    color: #409eff;
  }
</style>
